package order

type tOrderServiceImplement struct {
}

func newOrderServiceImplement() IOrderService {
	it := new(tOrderServiceImplement)
	return it
}

func (me *tOrderServiceImplement) Create(header *OrderHeaderDTO, items []*OrderItemDTO) IOrder {
	ret := []IOrder{nil}
	_ = MockOrderRepository.Transaction(func() error {
		hd := new(tOrderHeaderEntity)
		hd.Read(header)
		hd.OrderID = MockOrderRepository.NewOrderID()
		e, he := MockOrderRepository.SaveOrderHeader(hd)
		if e != nil {
			return e
		}

		for _, v := range items {
			item := new(tOrderItemEntity)
			item.Read(v)
			item.ItemID = MockOrderRepository.NewItemID()
			item.OrderID = he.OrderID
			e, _ = MockOrderRepository.SaveOrderItem(item)
			if e != nil {
				return e
			}
		}

		ret[0] = newOrderImplement(he)
		return nil
	})

	return ret[0]
}

func (me *tOrderServiceImplement) Get(orderId int64) IOrder {
	e, hd := MockOrderRepository.LoadOrderHeader(orderId)
	if e != nil {
		return nil
	}

	return newOrderImplement(hd)
}

var OrderService = newOrderServiceImplement()
